﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.ServiceModel;
using System.Xml.Linq;
using DevWeb.Biztalk.DeploymentSettings.DeploymentService.ClientProxy;
using DevWeb.Biztalk.DeploymentSettings.DeploymentService.ClientProxy.ChannelPattern;
using DevWeb.Biztalk.DeploymentSettings.DeploymentService.Contracts;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System.IO;


namespace HG.INF.BizTalk.DeploymentFramework.Tasks
{
    public class GetEnvironmentSettingsTasks : Task
    {
        [Required]
        public string ProjectName { get; set; }

        [Required]
        public string ProductId { get; set; }

        [Required]
        public string ProductUpgradeCode { get; set; }

        [Required]
        public string Version { get; set; }

        [Required]
        public string SettingFilePath { get; set; }

        [Required]
        public string ServiceAddress { get; set; }


        private string _environment = string.Empty;

        public override bool Execute()
        {



            FileInfo fi = new FileInfo(SettingFilePath);
            if (!fi.Exists)
            {
                using (var fs= fi.Create())
                {
                    fs.Flush();
                    
                }
                
            }
           
                
                
            string logmsg =
                string.Format(
                    "User {4} called GetEnvironmentSettingsTasks for integration {0} with version : {1} (ProductId:{2}) (ProductUpgradeCode{3}) on date: {5}",
                    ProjectName, Version, ProductUpgradeCode, ProductId, Environment.UserName, DateTime.Now.ToString(CultureInfo.InvariantCulture));
            

            Log.LogMessage(MessageImportance.High,logmsg );

            var settings =GetSettings().OrderBy(p=>p.ParameterName);

            
            Log.LogMessage(MessageImportance.High, string.Format("Found {0} settings for this integration ", settings.Count()));
            WriteXmlFile(SettingFilePath, settings, ProductId, ProductUpgradeCode, ProjectName, logmsg);

            return true;
        }

        private void WriteXmlFile(string settingsfilepath, IEnumerable<DevWeb.Biztalk.DeploymentSettings.Data.T4.IntegrationVersionSettings> settings, string ProductId, string ProductUpgradeCode, string ProjectName, string header)
        {




            var doc = new XDocument(new XComment(header));

            
            var rootElement = new XElement("settings");

            foreach (var integrationVersionSettingItem in settings)
            {
                var itemElement = new XElement("property", new XAttribute("name", integrationVersionSettingItem.ParameterName), GetSettingValue(integrationVersionSettingItem));
                if (integrationVersionSettingItem.IntegrationVersionID == -1)
                {
                    itemElement.Add(new XAttribute("Default","true"));
                }
                rootElement.Add(itemElement);
            }

            doc.Add(rootElement);

           doc.Save(settingsfilepath);
           Log.LogMessage(MessageImportance.High, string.Format("Settings saved  to {0} settings for this integration ",SettingFilePath));
        
        }

        private string GetSettingValue(DevWeb.Biztalk.DeploymentSettings.Data.T4.IntegrationVersionSettings item)
        {
            string result;
            switch (_environment)
            {
                case "DEV":
                    result = string.IsNullOrEmpty(item.DevValue)? item.DefaultValue:
                    item.DevValue;
                    break;
                case "TST":
                     result = string.IsNullOrEmpty(item.TestValue)? item.DefaultValue:
                    item.TestValue;
                    break;
                case "ACC":
                    result = string.IsNullOrEmpty(item.AccValue) ? item.DefaultValue :
                   item.AccValue;
                    break;

                case "PRD":
                    result = string.IsNullOrEmpty(item.ProdValue) ? item.DefaultValue :
                   item.ProdValue;
                    break;
                 default:
                    result = item.DefaultValue;
                    break;
            }

            return result;
        }

        private IEnumerable<DevWeb.Biztalk.DeploymentSettings.Data.T4.IntegrationVersionSettings> GetSettings()
        {

            var binding = new WSHttpBinding();
            var endpointaddress = new EndpointAddress(ServiceAddress);

            var client = new ProxyClient<IDeploymentSettingsService>(endpointaddress,binding).Client;
            
            var productupgragdecode = Guid.Parse(ProductUpgradeCode);
            var productid = Guid.Parse(ProductId);
            _environment = Environment.GetEnvironmentVariable("BTDFENV");

            var settings = client.GetEnvironmentSettings(productupgragdecode, productid, _environment);
            return settings.AsEnumerable();
        }

        
    }
}
